package cn.edu.hnu.gpg.api;

import cn.edu.hnu.gpg.api.error.*;
import cn.edu.hnu.gpg.dto.Account;
import cn.edu.hnu.gpg.dto.Questions;
import cn.edu.hnu.gpg.dto.Review;
import cn.edu.hnu.gpg.dto.Teacherno;
import cn.edu.hnu.gpg.entity.*;
import cn.edu.hnu.gpg.service.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/api/student")
public class StudentApiController {
    static private final Logger logger = LogManager.getLogger(StudentApiController.class);

//    @Autowired
//    private HttpSession session;
//    @Autowired
//    private HttpServletRequest request;
    private final QuestionService questionService;
    private final StudentService studentService;
    private final SupervisionService supervisionService;
    private final AnswerService answerService;
    private final TeacherReviewService teacherReviewService;
    @Autowired
    public StudentApiController(StudentService studentService,QuestionService questionService,SupervisionService supervisionService,AnswerService answerService,TeacherReviewService teacherReviewService){
        this.studentService = studentService;
        this.questionService = questionService;
        this.supervisionService = supervisionService;
        this.answerService = answerService;
        this.teacherReviewService = teacherReviewService;
    }

    @RequestMapping(value = "add_question", method = RequestMethod.POST)
    @ResponseBody
    public void addQuestion(HttpServletRequest request,@RequestBody Questions questions) throws InvalidArgumentException, FailedPreconditionException, UnknownException {
        try {
            String subject = questions.getSubject();String description = questions.getDescription();
            if (subject.isEmpty() || description.isEmpty()){
                throw new InvalidArgumentException("输入的问题无效！！！");
            }
            logger.info("subject"+subject+" description " + description);
            User user = (User) request.getSession(true).getAttribute("user");
            questionService.CreateQuestion(subject,description, user.getUserId());
        } catch (DataAccessException e) {
            throw new FailedPreconditionException(new ApiError(ApiError.ErrorType.ERR_CONSTRAINT_VIOLATION, e.getCause().getMessage()));
        } catch (IllegalStateException e) {
            throw new InvalidArgumentException(e.getMessage());
        } catch (Exception e) {
            throw new UnknownException(e.getMessage());
        }
    }

    @RequestMapping(value = "search_student", method = RequestMethod.GET)
    @ResponseBody
    public Student searchAccounts(HttpServletRequest request) throws InvalidArgumentException {
        User user = (User)request.getSession(true).getAttribute("user");
//        int user_id = user.getUserId();
//        Account account = new Account(studentService.findStudentByUserId(user_id));
//        logger.info(account.getUserType());
//        List<Account> l = new ArrayList<>();
//        l.add(account);
//        return l;
        Student student = studentService.findStudentByUserId(user.getUserId());
        logger.info(student.getStudentNumber());
        return student;
    }

    @RequestMapping(value = "select_teacher", method = RequestMethod.POST)
    @ResponseBody
    public void selectTeacher(HttpServletRequest request,@RequestBody Teacherno teacherno) throws InvalidArgumentException, FailedPreconditionException, UnknownException {
        try {
            String teacher_no = teacherno.getTeacher_no();
            if (teacher_no.isEmpty()){
                throw new InvalidArgumentException("输入的教师工号无效！！！");
            }
            logger.info("teacher_no"+teacher_no);
            User user = (User) request.getSession(true).getAttribute("user");
            supervisionService.createSupervision(user,teacher_no);
        } catch (DataAccessException e) {
            throw new FailedPreconditionException(new ApiError(ApiError.ErrorType.ERR_CONSTRAINT_VIOLATION, e.getCause().getMessage()));
        } catch (IllegalStateException e) {
            throw new InvalidArgumentException(e.getMessage());
        } catch (Exception e) {
            throw new UnknownException(e.getMessage());
        }
    }

    @RequestMapping(value = "do_review", method = RequestMethod.POST)
    @ResponseBody
    public void addReview(HttpServletRequest request,@RequestBody Review review) throws InvalidArgumentException, FailedPreconditionException, UnknownException {
        try {
            String comment = review.getComment();
            int count = review.getCount();
            logger.info("oldCOUNT"+count);
            if (count<=16)
                count = 1;
            else
                count = (count-16)/8+1;
            logger.info("COUNT "+count+" Comment" + comment);
            User user = (User) request.getSession(true).getAttribute("user");
            byte rating = (byte)count;
            if (comment.isEmpty())
                comment="此用户未做其他评价！！！";
            Student student = studentService.findStudentByUserId(user.getUserId());
            if (student == null)
                throw new IllegalArgumentException("student error!!!");

            teacherReviewService.createNewReview(student.getStudentId(),rating,comment);
        } catch (DataAccessException e) {
            throw new FailedPreconditionException(new ApiError(ApiError.ErrorType.ERR_CONSTRAINT_VIOLATION, e.getCause().getMessage()));
        } catch (IllegalStateException e) {
            throw new InvalidArgumentException(e.getMessage());
        } catch (Exception e) {
            throw new UnknownException(e.getMessage());
        }
    }

    @RequestMapping(value = "/{questionId}", method = RequestMethod.GET)
    @ResponseBody
    public Answer requestAnswer(HttpServletRequest request,@PathVariable Integer questionId) throws NotFoundException, UnknownException {
        try {
            Answer answer = answerService.getAllAnswerToQuestion(questionId).get(0);
            if (answer == null)
                throw new NotFoundException("Requested answer is not found");
            logger.info("answer:"+answer.getContent());
            return answer;

        } catch (Exception e) {
            logger.debug(e.getCause());
            throw new UnknownException();
        }
    }

    @RequestMapping(value = "my_question", method = RequestMethod.GET)
    @ResponseBody
    public List<Question> selectMyQuestion(HttpServletRequest request) throws InvalidArgumentException, FailedPreconditionException, UnknownException {
        try {
            User user = (User)request.getSession(true).getAttribute("user");
            int user_id = user.getUserId();
            return questionService.findQuestionByUserId(user_id);
        } catch (DataAccessException e) {
            throw new FailedPreconditionException(new ApiError(ApiError.ErrorType.ERR_CONSTRAINT_VIOLATION, e.getCause().getMessage()));
        } catch (IllegalStateException e) {
            throw new InvalidArgumentException(e.getMessage());
        } catch (Exception e) {
            throw new UnknownException(e.getMessage());
        }
    }


}
